﻿using Gecko.Models;
using Gecko.Models.Dto;
using Gecko.Services;
using Gecko.Util;
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using System.Web.Http;
using System.Web.Http.Routing;

namespace Gecko.Controllers
{
    public class WaterLeakController : ApiController
    {
        // GET api/waterleak
        public ServiceResponse<IList<WaterLeakDto>> Get()
        {
            using (var waterLeakService = new WaterLeakService())
            {
                var result = waterLeakService.GetAllWaterLeak();
                foreach (var item in result.Data)
                {
                    if (!String.IsNullOrEmpty(item.Url))
                    {
                        var urlHelper = new UrlHelper(Request);
                        item.Url = urlHelper.Link("DefaultApi", new { controller = "LeakContent", id = item.Url });
                    }
                }
                return result;
            }
        }

        // GET api/waterleak/5
        public ServiceResponse<WaterLeakFullResDto> Get(int id)
        {
            using (var waterLeakService = new WaterLeakService())
            {
                var result = waterLeakService.GetById(id);
                var urlHelper = new UrlHelper(Request);
                if (result.Data != null)
                {
                    if (!String.IsNullOrEmpty(result.Data.Resource1))
                    {
                        result.Data.Resource1 = urlHelper.Link("DefaultApi", new { controller = "LeakContent", id = result.Data.Resource1 });
                    }
                    if (!String.IsNullOrEmpty(result.Data.Resource2))
                    {

                        result.Data.Resource2 = urlHelper.Link("DefaultApi", new { controller = "LeakContent", id = result.Data.Resource2 });
                    }
                    if (!String.IsNullOrEmpty(result.Data.Resource3))
                    {

                        result.Data.Resource3 = urlHelper.Link("DefaultApi", new { controller = "LeakContent", id = result.Data.Resource3 });
                    }
                }
                return result;
            }
        }

        private static byte[] ReadFully(Stream input)
        {
            byte[] buffer = new byte[16 * 1024];
            using (MemoryStream ms = new MemoryStream())
            {
                int read;
                while ((read = input.Read(buffer, 0, buffer.Length)) > 0)
                {
                    ms.Write(buffer, 0, read);
                }
                return ms.ToArray();
            }
        }

        public async Task<Object> Post()
        {

            try
            {
                if (!Request.Content.IsMimeMultipartContent("form-data"))
                {
                    throw new HttpResponseException(HttpStatusCode.BadRequest);
                }
                var provider = await Request.Content.ReadAsMultipartAsync<InMemoryMultipartFormDataStreamProvider>(new InMemoryMultipartFormDataStreamProvider());
                //access form data
                NameValueCollection formData = provider.FormData;

                double latPoint = 0;
                double.TryParse(formData["LatPoint"], out latPoint);

                double longPoint = 0;
                double.TryParse(formData["LongPoint"], out longPoint);

                WaterLeakDto waterLeakDto = new WaterLeakDto
                {
                    Detail = formData["Detail"],
                    LatPoint = latPoint,
                    LongPoint = longPoint,
                    Topic = formData["Topic"],
                    UserId = formData["UserId"]
                };

                ServiceResponse<WaterLeakDto> response;
                using (var waterLeakService = new WaterLeakService())
                {
                    response = waterLeakService.AddWaterLeak(waterLeakDto);
                }
                if (response.Status && response.Data.Id != 0)
                {
                    using (var waterLeakResourceService = new WaterLeakResourceService())
                    {
                        var resources = new List<WaterLeakResourceModel>();
                        foreach (var item in provider.Files)
                        {
                            Stream image = await item.ReadAsStreamAsync();
                            if (item.Headers.ContentLength.Value > 0)
                            {
                                resources.Add(new WaterLeakResourceModel
                                {
                                    MediaType = item.Headers.ContentType.MediaType,
                                    Size = item.Headers.ContentLength.Value,
                                    Resource = ReadFully(image)
                                });
                            }
                        }
                        waterLeakResourceService.AddWaterLeakResource(response.Data.Id, resources);
                    }
                    return new
                    {
                        Status = true,
                        Message = "Success"
                    };
                }
                throw new Exception("Insert Fail.");
            }
            catch (Exception e)
            {
                return new
                           {
                               Status = false,
                               Message = e.Message
                           };
            }
            
        }
        

        // POST api/waterleak
        //public ServiceResponse<WaterLeakDto> Post(WaterLeakDto waterLeakDto)
        //{
        //    using (var waterLeakService = new WaterLeakService())
        //    {
        //        return waterLeakService.AddWaterLeak(waterLeakDto);
        //    }
        //}

        // PUT api/waterleak/5
        public void Put(int id, [FromBody]string value)
        {
        }

        // DELETE api/waterleak/5
        public void Delete(int id)
        {
        }
    }
}
